<template>
  <div class="content">
    <MainPage v-show="pageType === 'index'" :title="'项目列表'" class="mainContent">
      <div v-if="projectSumNumber > 0 || loading" v-loading="loading" class="projectContent">
        <div class="searchDiv">
          项目名称：
          <el-input
            v-model="search.name"
            placeholder="请输入项目名称"
            class="searchInput"
            @keyup.enter.native="searchClick"
          />
          <el-button type="primary" class="topBtn" @click="searchClick">查询</el-button>
          <el-button class="topBtn" @click="clearClick">重置</el-button>
          <el-button
            class="disabledBtn"
            :disabled="selectedForBatchDelete.length === 0"
            @click="showDeleteConfirmation"
          >
            批量删除
          </el-button>
        </div>
        <div v-if="projectData.length > 0 || loading" class="templateContent">
          <div class="addItem">
            <el-button type="primary" @click="handleClick('add')">创建项目</el-button>
          </div>
          <div
            v-for="(item, index) in projectData"
            :key="'template' + index"
            :class="item.selected ? 'item item-selected' : 'item'"
          >
            <!--复选框-->
            <div class="custom-checkbox">
              <el-checkbox v-model="item.selected" class="checkbox" @change="updateSelectedForBatchDelete(item)" />
            </div>
            <div class="header">
              <el-tooltip :disabled="getStrLength(item.name) <= 18" :content="item.name" placement="top">
                <div class="title">项目名称：{{ item.name }}</div>
              </el-tooltip>
              <!-- <div class="updateTime">最后编辑时间：{{ item.updateTime }}</div> -->
              <el-tooltip
                :disabled="getStrLength(item.description) <= 38"
                :content="item.description"
                placement="top"
              >
                <div class="description ellipsis">{{ item.description }}</div>
              </el-tooltip>
            </div>
            <div class="btnContent">
              <div class="btn">
                <el-link type="primary" :underline="false" @click="handleClick('edit', item, index)">
                  编辑信息
                </el-link>
                <el-divider direction="vertical" />
                <el-link type="primary" :underline="false" @click="handleClick('open', item, index)">
                  打开项目
                </el-link>
                <el-divider direction="vertical" />
                <el-popconfirm title="确定删除本项目吗？" @confirm="handleClick('del', item, index)">
                  <el-link slot="reference" type="primary" :underline="false" class="delBtn">删除</el-link>
                </el-popconfirm>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="emptyContent">
          <el-empty :image="require('@/assets/imgs/empty.png')" description="数据为空">
            <el-button type="primary" @click="handleClick('add')">创建项目</el-button>
          </el-empty>
        </div>
      </div>
      <div v-else class="projectContent">
        <div class="emptyContent">
          <el-empty :image="require('@/assets/imgs/empty.png')" description="暂未创建项目">
            <el-button type="primary" @click="handleClick('add')">创建项目</el-button>
          </el-empty>
        </div>
      </div>
    </MainPage>
    <div v-show="pageType === 'openProject'" class="mainContent">
      <openProject
        ref="openProject"
        :project-data="currentProjectData"
        @changeCurrentTag="changeCurrentTag"
        @initCurrentProject="initCurrentProject"
      />
    </div>
    <projectDetail ref="projectDetail" @refreshData="refreshData" />
    <tagsView ref="tagsView" :tags-data="openProjectData" @changePageType="changePageType" />
  </div>
</template>
<script>
import {
  getProjectList,
  initProject,
  deleteProject,
  initConfig,
  deleteBatchProject
} from '@/api/project-management'
import { getStrLength } from '@/utils/index'
import tagsView from './components/tagsView'
import projectDetail from './components/projectDetail.vue'
import openProject from './components/openProject.vue'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
export default {
  name: 'ProjectList',
  components: { tagsView, openProject, projectDetail },
  data() {
    return {
      loading: true,
      pageType: 'index',
      search: { name: '' },
      projectSumNumber: 0,
      projectData: [],
      openProjectData: [],
      currentProjectData: {},
      getListRequestId: generateUUID(),
      initProjectRequestId: generateUUID(),
      openType: '',
      deleteProjectRequestId: generateUUID(),
      deleteBatchProjectRequestId: generateUUID(),
      currentRow: {},
      currentIndex: 0,
      initConfigRequestId: generateUUID(),
      currentProject: {},
      initCurrentProjectRequestId: generateUUID(),
      selectedForBatchDelete: [],
      deleteConfirmationVisible: false
    }
  },
  created() {
    this.searchClick()
  },
  mounted() {
    receivedMessage(this.dataHandle)
    this.$refs.openProject.initData()
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      if (e.data.webInfo.requestId === self.getListRequestId) {
        self.projectData = e.data.response.data.projectList
        self.projectData.forEach((item) => {
          item.selected = false
        })
        self.projectSumNumber = e.data.response.data.projectSumNumber
        self.loading = false
      } else if (e.data.webInfo.requestId === self.initProjectRequestId) {
        self.$refs.projectDetail.is(self.openType, e.data.response.data)
      } else if (e.data.webInfo.requestId === self.deleteProjectRequestId) {
        self.handleDel(e.data.response)
      } else if (e.data.webInfo.requestId === self.initConfigRequestId) {
        self.openProjectWindow(e.data.response)
      } else if (e.data.webInfo.requestId === self.initCurrentProjectRequestId) {
        let res = e.data.response
        if (res.success) {
          self.currentProject.layoutContent = res.data.layoutContent
          self.$refs.openProject.$refs.chipFlowChart.initData(self.currentProject.layoutContent)
        } else {
          self.$message.error(res.message)
        }
      } else if (e.data.webInfo.requestId === self.deleteBatchProjectRequestId) {
        self.handleBatchDelete(e.data.response)
      }
    },
    searchClick() {
      this.loading = true
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.getListRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/project/getList',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: { name: this.search.name },
          WebInfo: {
            requestId: this.getListRequestId
          }
        }
        postMessage(message)
      } else {
        getProjectList({ name: this.search.name }).then((res) => {
          this.projectData = res.data.projectList
          // 初始化每个项目的 selected 属性为 false
          this.projectData.forEach((item) => {
            item.selected = false
          })
          this.projectSumNumber = res.data.projectSumNumber
          this.loading = false
        })
      }
    },
    clearClick() {
      this.search.name = ''
      this.searchClick()
      this.selectedForBatchDelete = []
    },
    getStrLength(str) {
      return getStrLength(str)
    },
    showDeleteConfirmationModal() {
      if (this.selectedForBatchDelete.length > 0) {
        this.deleteConfirmationVisible = true
      }
    },
    handleClick(name, row, index) {
      if (name === 'add') {
        this.$refs.projectDetail.is(name, {})
      } else if (name === 'edit') {
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.openType = name
          this.initProjectRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/project/init',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: { projectId: row.projectId },
            WebInfo: {
              requestId: this.initProjectRequestId
            }
          }
          postMessage(message)
        } else {
          initProject({ projectId: row.projectId }).then((res) => {
            this.$refs.projectDetail.is(name, res.data)
          })
        }
      } else if (name === 'del') {
        this.currentRow = row
        this.currentIndex = index
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.deleteProjectRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/project/delete',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: { projectId: row.projectId },
            WebInfo: {
              requestId: this.deleteProjectRequestId
            }
          }
          postMessage(message)
        } else {
          deleteProject({ projectId: row.projectId }).then((res) => {
            this.handleDel(res)
          })
        }
      } else if (name === 'batchDelete') {
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.deleteBatchProjectRequestId = generateUUID()
          const requestData = {
            projectIds: this.selectedForBatchDelete
          }

          const message = {
            RequestUrl: process.env.VUE_APP_URL + '/project/deleteBatch',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: requestData,
            WebInfo: {
              requestId: this.deleteBatchProjectRequestId
            }
          }
          postMessage(message)
        } else {
          // 批量删除请求
          const requestData = {
            projectIds: this.selectedForBatchDelete
          }

          deleteBatchProject(requestData) // 假设你的 API 请求方法是 deleteBatchProject
            .then((res) => {
              // 批量删除成功
              this.handleBatchDelete(res)
            })
            .catch((error) => {
              // 批量删除失败，进行错误处理
              console.error('批量删除失败：', error)
            })
        }
      } else if (name === 'open') {
        let isOpen = this.openProjectData.findIndex((item) => item.projectId === row.projectId)
        if (isOpen === -1) {
          this.currentRow = row
          if (defaultSettings.isWPF || defaultSettings.isCEF) {
            this.initConfigRequestId = generateUUID()
            let message = {
              RequestUrl: process.env.VUE_APP_URL + '/project/initConfig',
              RequestMethod: 'POST',
              Headers: {
                contentType: 'application/json'
              },
              QueryParameter: {},
              RequestBody: { projectId: row.projectId },
              WebInfo: {
                requestId: this.initConfigRequestId
              }
            }
            postMessage(message)
          } else {
            initConfig({ projectId: row.projectId }).then((res) => {
              this.openProjectWindow(res)
            })
          }
        } else {
          this.$refs.tagsView.handleSelectedTag(row)
        }
      }
    },
    openProjectWindow(res) {
      if (res.success) {
        this.openProjectData.push({
          ...res.data,
          saved: true
        })
        this.$refs.tagsView.handleSelectedTag(this.currentRow)
      } else {
        this.$message.error(res.message)
      }
    },
    handleDel(res) {
      if (res.success) {
        this.$message.success('删除成功')
        this.projectData.splice(this.currentIndex, 1)
        this.openProjectData.splice(
          this.openProjectData.findIndex((item) => item.projectId === this.currentRow.projectId),
          1
        )
        // 根据ID删除选择的项目
        this.selectedForBatchDelete = this.selectedForBatchDelete.filter((i) => i !== this.currentRow.projectId)
      } else {
        this.$message.error(res.message)
      }
    },
    showDeleteConfirmation() {
      this.$confirm('确定要删除选择的项目？', '确认删除', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 用户点击了确认按钮，执行删除操作
          this.handleClick('batchDelete', null, null)
        })
        .catch(() => {
          // 用户点击了取消按钮，什么都不做
        })
    },
    handleBatchDelete(res) {
      if (res.success) {
        this.$message.success('批量删除成功')
        // 清空选中的项目
        this.selectedForBatchDelete = []
        // 设置所有checkbox为未选中状态
        this.projectData.forEach((item) => {
          item.selected = false
        })
        this.clearClick()
      } else {
        this.$message.error(res.message)
      }
    },
    refreshData(type = '', data = {}) {
      this.searchClick()
      if (type === 'add') {
        this.handleClick('open', data)
      } else {
        let currentProject = this.openProjectData.find((item) => item.projectId === data.projectId)
        currentProject.name = data.name
      }
    },
    initCurrentProject(projectId) {
      this.currentProject = this.openProjectData.find((item) => item.projectId === projectId)
      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.initCurrentProjectRequestId = generateUUID()
        let message = {
          RequestUrl: process.env.VUE_APP_URL + '/project/initConfig',
          RequestMethod: 'POST',
          Headers: {
            contentType: 'application/json'
          },
          QueryParameter: {},
          RequestBody: { projectId: projectId },
          WebInfo: {
            requestId: this.initCurrentProjectRequestId
          }
        }
        postMessage(message)
      } else {
        initConfig({ projectId: projectId }).then((res) => {
          this.currentProject.layoutContent = res.data.layoutContent
          this.$refs.openProject.$refs.chipFlowChart.initData(this.currentProject.layoutContent)
        })
      }
    },
    changeCurrentTag(isSaved) {
      this.$refs.tagsView.changeSaved(isSaved)
    },
    changePageType(val, oldValue) {
      if (oldValue) {
        let history = this.openProjectData.find((item) => item.projectId === oldValue)
        if (history) {
          history.layoutContent = this.$refs.openProject.$refs.chipFlowChart.getChartData()
        }
      }
      if (val) {
        this.pageType = 'openProject'
        this.currentProjectData = this.openProjectData.find((item) => item.projectId === val)
        this.$nextTick(() => {
          this.$refs.openProject.$refs.chipFlowChart.initData(this.currentProjectData.layoutContent)
        })
      } else {
        this.pageType = 'index'
      }
    },
    updateSelectedForBatchDelete(item) {
      if (item.selected) {
        this.selectedForBatchDelete.push(item.projectId)
      } else {
        this.selectedForBatchDelete = this.selectedForBatchDelete.filter((i) => i !== item.projectId)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/element-variables.scss';

.content {
  height: 100%;
  display: flex;
  flex-direction: column;

  .mainContent {
    flex: 1;
    height: calc(100% - 36px);

    .projectContent {
      height: 100%;
      display: flex;
      flex-direction: column;

      .emptyContent {
        width: 75%;
        margin: 0 auto;
        margin-top: 120px;
        background-color: #f7f8fa;
      }
    }

    .searchDiv {
      margin-bottom: 10px;
      position: relative;

      .searchInput {
        width: 300px;
        padding-right: 0;
        margin-right: 15px;
      }
    }

    .templateContent {
      display: flex;
      flex-wrap: wrap;
      flex: 1;
      overflow-y: auto;
      align-content: baseline;

      .addItem {
        padding: 20px;
        // border: 1px dashed #d1e2f5;
        background: #f7f8fa;
        border-radius: 4px;
        margin-right: 10px;
        width: 300px;
        height: 150px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        font-family: Source Han Sans CN-Bold, Source Han Sans CN;
        font-weight: bold;
        color: #333333;
      }

      .addItem:hover {
        border: 1px dotted $--color-primary;
      }

      .item {
        padding: 24px 20px;
        border: 1px solid #dde4ec;
        border-radius: 4px;
        margin-right: 10px;
        margin-bottom: 10px;
        width: 300px;
        height: 150px;
        background-color: #fcfdff;
        position: relative;

        .header {
          // display: flex;
          // align-items: center;
          color: #303453;

          .title {
            font-size: 16px;
            font-family: Source Han Sans CN-Bold, Source Han Sans CN;
            font-weight: bold;

            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            width: calc(100% - 32px);
          }

          .description {
            margin-top: 18px;
            width: 100%;
          }

          .updateTime {
            margin-top: 18px;
          }
        }

        .btnContent {
          position: absolute;
          bottom: 11px;
          left: 10px;
          width: 280px;
          border-top: 1px dashed #dde4ec;
          padding-top: 12px;

          .btn {
            display: flex;
            justify-content: space-around;
            align-items: center;
          }

          .delBtn {
            margin-bottom: 1px;
          }
        }
      }

      .item:hover {
        border: 1px solid $--color-primary;
      }
    }
  }

  .custom-checkbox {
    /* 将复选框放置在复选框容器的右上角 留出10px的空余 */
    position: absolute;
    top: 0;
    right: 0;
    margin: 10px;
    /* 设置无边框 */
    border: none;
  }

  .checkbox /deep/ .el-checkbox__input {
    /*使用CSS3的transform属性来调整复选框的大小,官方的Size仅支持有边框,本组件无边框*/
    transform: scale(1.5); /* 调整缩放级别 */
    -webkit-transform: scale(1.5); //for Chrome || Safari
    -moz-transform: scale(1.5); //for Firefox
    -ms-transform: scale(1.5); //for IE
    -o-transform: scale(1.5); //for Opera
  }

  .item-selected {
    background-color: #fff4f7 !important;
  }
}
</style>
